#!/bin/sh

. /usr/share/common

IFACE=wlan0
CONFIG="/etc/$DAEMON_SHORT.conf"
PIDFILE="/run/$DAEMON_SHORT.$IFACE.pid"
WLAN_INT_FILE="/etc/network/interfaces.d/wlan0"
DAEMON_ARGS="-i $IFACE -c $CONFIG -P $PIDFILE -B"

if [ "true" = "$debug" ]; then
	DAEMON_ARGS="$DAEMON_ARGS -dd"
fi

password_changed() {
	old_pass=$(awk -F= '/^\s*psk=/{gsub(/^"|"$/, "", $2); print $2}' $CONFIG)
	[ "$old_pass" != "$wlan_pass" ]
}

ssid_changed() {
	old_ssid=$(awk -F= '/^\s*ssid=/{gsub(/^"|"$/, "", $2); print $2}' $CONFIG)
	[ "$old_ssid" != "$wlan_ssid" ]
}

start() {
	echo_title "Starting WPA Supplicant"

	# convert plain-text password no matter what
	if [ -n "$wlan_pass" ] && [ ${#wlan_pass} -lt 64 ]; then
		tmpfile=$(mktemp)
		wpa_passphrase "$wlan_ssid" "$wlan_pass" > $tmpfile
		wlan_pass=$(grep '^\s*psk=' $tmpfile | cut -d= -f2 | tail -n 1)
		fw_setenv wlan_pass $wlan_pass
		rm -f $tmpfile
	fi

	if ! iface_exists "wlan0"; then
		echo_error "No wireless interface"
		exit 1
	fi

	if [ -z "$wlan_pass" ]; then
		echo_error "WiFi password missing"
	fi

	if [ -z "${wlan_ssid}${wlan_bssid}" ]; then
		echo_error "WiFi network missing"
		exit 1
	fi

	if grep -q "^#auto wlan0" $WLAN_INT_FILE; then
		echo_error "wlan0 manually disabled"
		exit 1
	fi

	if [ ! -f "$CONFIG" ] || ssid_changed || password_changed; then
		wpa_passphrase "$wlan_ssid" "dummy_password" > $CONFIG
		sed -i "s/psk=.*$/psk=${wlan_pass}/" $CONFIG
		if [ -n "$wlan_bssid" ]; then
			sed -i "s/^\s*ssid=.*$/\tbssid=$wlan_bssid/" $CONFIG
		else
			sed -i '/}/i\\tscan_ssid=1' $CONFIG
		fi
	fi

	if [ "true" = "$wlanap_enabled" ]; then
		echo_error "WLAN AP enabled"
		exit 1
	fi

	start-stop-daemon -S -x $DAEMON_FULL -- $DAEMON_ARGS 2>&1
}

stop() {
	echo_title "Stopping WPA Supplicant"

	stop_daemon
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		stop
		start
		;;
	*)
		echo "Usage: $0 {start|stop|restart|reload}"
		exit 1
		;;
esac

exit 0
